package indi.bamboo.generate.mapper;

import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * @ClassName PostgreTableMapper
 * @Description Postgre数据库表映射器接口
 * @Author Bamboo aspbamboo@gmail.com
 * @Date 2021/4/16 14:23
 * @Version 1.0
 */
public interface PostgreTableMapper extends TableMapper {

    /**
     * 查询所有表名及其说明
     *
     * @param databaseName 数据库名称
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author Bamboo aspbamboo@gmail.com
     * @date 2021/04/16 14:31:23
     */
    @Override
    @Select("SELECT " +
            "   tablename AS name, " +
            "   CAST ( " +
            "      obj_description (relfilenode, 'pg_class') AS VARCHAR " +
            "   ) AS comment " +
            "FROM " +
            "   pg_tables t1 " +
            "INNER JOIN pg_class t2 " +
            "        ON t1.tablename = t2.relname " +
            "WHERE " +
            "   tablename NOT LIKE'pg%'  " +
            "   AND tablename NOT LIKE'sql_%'  " +
            "ORDER BY " +
            "   tablename;")
    List<Map<String, Object>> selectAllTable(String databaseName);

    /**
     * 查询当前表所有字段
     * SELECT * FROM mysql.`INNODB_INDEX_STATS` WHERE table_name = 'table_name'; 查询索引
     *
     * @param tableName 表名
     * @return java.util.List
     * @author Bamboo aspbamboo@gmail.com
     * @date 2018/11/08 17:27:46
     */
    @Override
    @Select("SELECT  " +
            "   t2.attname AS NAME, " +
            "   format_type ( t2.atttypid, t2.atttypmod ) AS DATA_TYPE, " +
            "   '' AS DATA_LENGTH, " +
            "   t2.attnotnull != TRUE AS ISNULL, " +
            "   (    CASE WHEN ( SELECT COUNT(*) FROM pg_constraint WHERE conrelid = t2.attrelid AND conkey[1]= attnum AND contype ='p' ) >0THEN " +
            "        TRUE ELSE FALSE  " +
            "END ) AS COLUMN_KEY, " +
            "   col_description ( t2.attrelid, t2.attnum ) AS COMMENT, " +
            "   t3.column_default AS DEFAULT_VALUE, " +
            "   CASE t2.attname " +
            "   WHEN 'id' THEN 1 " +
            "   WHEN 'create_user_id' THEN 3 " +
            "   WHEN 'update_user_id' THEN 4 " +
            "   WHEN 'create_time' THEN 5 " +
            "   WHEN 'update_time' THEN 6 " +
            "   WHEN 'is_delete' THEN 7 " +
            "   WHEN 'version' THEN 8 " +
            "   ELSE 2 END SORT " +
            "FROM " +
            "   pg_class t1, " +
            "   pg_attribute t2, " +
            "   information_schema.columns t3 " +
            "WHERE " +
            "   t1.relname = #{tableName} " +
            "   AND t2.attrelid = t1.oid " +
            "   AND t2.attnum > 0 " +
            "   AND t3.table_name = t1.relname AND t3.column_name = t2.attname ")
    List<Map<String, String>> selectFields(String tableName);
}